package io.renren.modules.sys.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import io.renren.common.utils.Result;
import io.renren.modules.sys.dto.QAnswerDTO;
import io.renren.modules.sys.entity.QAnswer;
import io.renren.modules.sys.entity.QQuestion;
import io.renren.modules.sys.service.QAnswerService;
import io.renren.modules.sys.service.QAnswererService;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


/**
 * (QAnswer)表控制层
 *
 * @author makejava
 * @since 2024-07-03 16:23:56
 */
@RestController
@RequestMapping("qAnswer")
public class QAnswerController {
    /**
     * 服务对象
     */
    @Resource
    private QAnswerService qAnswerService;

    @Resource
    private QAnswererService qAnswererService;

    /**
     * 分页查询
     *
     * @param qAnswer 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<QAnswer>> queryByPage(QAnswer qAnswer, PageRequest pageRequest) {
        return ResponseEntity.ok(this.qAnswerService.queryByPage(qAnswer, pageRequest));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<QAnswer> queryById(@PathVariable("id") String id) {
        return ResponseEntity.ok(this.qAnswerService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param qAnswer 实体
     * @return 新增结果
     */
    @PostMapping
    public Result<QAnswer> add(@RequestBody QAnswer qAnswer) {
        qAnswer.setId(UUID.randomUUID().toString());
        return new Result<QAnswer>().ok(this.qAnswerService.insertOrUpdate(qAnswer));
    }

    /**
     * 编辑数据
     *
     * @param qAnswer 实体
     * @return 编辑结果
     */
    @PutMapping
    public ResponseEntity<QAnswer> edit(QAnswer qAnswer) {
        return ResponseEntity.ok(this.qAnswerService.update(qAnswer));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(String id) {
        return ResponseEntity.ok(this.qAnswerService.deleteById(id));
    }

    @GetMapping("/queryByAnswererId")
    public Result<List<QAnswerDTO>> queryByAnswererId(String answererId) {
        List<QQuestion> questions = new ArrayList<>();
        try {
            questions = this.qAnswererService.getQuestionsByAnswerersId(answererId);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        List<QAnswerDTO> result = this.qAnswerService.queryAnswersByAnswererIdAndQuestionId(answererId, questions.stream().map(QQuestion::getId).toList());
        return new Result<List<QAnswerDTO>>().ok(result);
    }

}

